import Cookies from 'js-cookie';
import config from '@/config';
const { cookieExpires } = config;
const TOKEN_KEY = 'token';

export const setToken = token => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 });
};
export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY);
  if (token) return token;
  else return false;
};
export const setCookie = (cookiename, obj) => {
  if (obj instanceof Object) {
    obj = JSON.stringify(obj);
  }
  Cookies.set(cookiename, obj, { expires: cookieExpires || 1 });
};
export const getCookie = cookiename => {
  let obj = Cookies.get(cookiename);
  if (obj && (obj.slice(0, 1) === '{' || obj.slice(0, 1) === '[')) {
    obj = JSON.parse(obj);
  }
  if (obj) return obj;
  else return null;
};

export const removeCookie = name => {
  Cookies.remove(name);
};

export const removeAll = name => {
  const array = ['cars', 'carinfo', 'cartype', 'company', 'staticurl'];
  array.forEach(item => {
    removeCookie(item)
  })
}



export const forEach = (arr, fn) => {
  if (!arr.length || !fn) return;
  let i = -1;
  let len = arr.length;
  while (++i < len) {
    let item = arr[i];
    fn(item, i, arr);
  }
};
